﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace library
{
    class Stats
    {
        double[] buffer = new double[Parameters.statsBufferSize];

        byte offset;

        DateTime beginGetPeer = DateTime.MinValue;

        DateTime last_requisition = DateTime.MinValue;

        internal bool IsBusy { get; private set; }

        internal double distance
        {
            get
            {
                double sum = 0;

                for (int i = 0; i < Parameters.statsBufferSize; i++)
                    sum += buffer[i];

                return sum / Parameters.statsBufferSize;
            }
        }

        internal Stats()
        {
            buffer = new double[Parameters.statsBufferSize];
        }

        internal void BeginGetPeer()
        {
            if (!beginGetPeer.Equals(DateTime.MinValue))
                EndGetPeer();

            beginGetPeer = DateTime.Now;
        }

        internal void EndGetPeer()
        {
            offset++;

            if (offset >= Parameters.statsBufferSize)
                offset = 0;

            buffer[offset] = (int)Math.Min(Parameters.time_out, DateTime.Now.Subtract(beginGetPeer).TotalMilliseconds);

            beginGetPeer = DateTime.MinValue;
        }

        internal bool HeIsDeadJim()
        {
            return distance.Equals(Parameters.time_out);
        }

        internal Stats(IEnumerable<double> data)
        {
            buffer = (double[])data;
        }

        internal IEnumerable<double> ToBytes()
        {
            return buffer;
        }

        Timer timer;

        internal void CountRequisition()
        {
            IsBusy = true;

            if (timer == null)
                timer = new Timer(TimerTask, null, Parameters.peers_interval, Timeout.Infinite);
            else
                timer.Change(Parameters.peers_interval, Timeout.Infinite);
        }
        
        void TimerTask(object o)
        {
            IsBusy = false;

            Peers.idlePeerEvent.Set();
        }

        
    }
}
